package email

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"regexp"
)

type Sender struct {
	User     string
	Password string
	Host     string
	Port     int
	MailTo   []string
	Subject  string
	Content  string
}

type Receiver struct {
	Email string
}

func (r *Receiver) Check() bool {
	pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(r.Email)
}

// NewReceiver 检查 邮箱正确性
func (s *Sender) NewReceiver(email string) *Receiver {
	rec := &Receiver{Email: email}
	if rec.Check() {
		s.MailTo = []string{email}
		return rec
	} else {
		fmt.Printf("email check fail 【%s】\n", email)
		return nil
	}
}
func (s *Sender) NewReceivers(receivers []*Receiver) {
	for _, rec := range receivers {
		if rec.Check() {
			s.MailTo = append(s.MailTo, rec.Email)
		} else {
			fmt.Printf("email check fail 【%s】\n", rec.Email)
		}
	}
}

func SendEmail(m Sender, receivers []*Receiver, name, subject, content string) {
	m.NewReceivers(receivers)
	m.Subject = subject
	m.Content = content

	e := gomail.NewMessage()
	e.SetHeader("From", e.FormatAddress(m.User, name))
	e.SetHeader("To", m.MailTo...)    //发送给多个用户
	e.SetHeader("Subject", m.Subject) //设置邮件主题
	e.SetBody("text/html", m.Content) //设置邮件正文
	d := gomail.NewDialer(m.Host, m.Port, m.User, m.Password)
	err := d.DialAndSend(e)
	if err != nil {
		fmt.Printf("error 邮件发送错误! %s  \n", err.Error())
	}
}
